from flask import Blueprint, request, current_app
from glob import glob
from os.path import join, split
import os
import time

api_blueprint = Blueprint("api_file_blueprint", __name__)


@api_blueprint.route("/getbooksfrombooksshelf")
def getbooksfrombooksshelf():
    res = list()
    for filepath in glob(join("bookshelf", "*")):
        suffix = filepath[filepath.rfind("."):]
        if suffix != '.cache':
            _, filename = split(filepath)
            res.append({
                "name": filename,
                "description": "创建时间：%s" % (time.strftime("%Y-%m-%d", time.localtime(os.stat(filepath).st_mtime)))
            })
    return {
        "files": res
    }


@api_blueprint.route("/getfilecontent")
def getfilecontent():
    bookname = request.args["bookname"]
    suffix = bookname[bookname.rfind("."):]
    reader = current_app.config['reader']
    reader.setmainreader(suffix)
    if reader.get_readfile_name() != bookname:
        if os.path.isfile(os.path.join("bookshelf", bookname)):
            bookpath = os.path.join("bookshelf", bookname)
            reader.readbook(bookpath)
        else:
            return {
                "pages": ["无效数据源"]
            }
    res = reader.get_pages()
    res = res[1::2]  # 排除重叠的页和扉页。
    res = [i.replace("\n", "<br>") for i in res]
    return {
        "pages": res
    }


def allowed_filename(filename):
    ALLOWED_EXTENSIONS = current_app.config['ALLOWED_EXTENSIONS']
    return '.' in filename and '.' + filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@api_blueprint.route("/fileupload", methods=['POST'])
def fileupload():
    if 'file' in request.files:
        f = request.files['file']
        if f.filename != '':
            if allowed_filename(f.filename):
                filename = f.filename
                f.save(os.path.join(current_app.config['UPLOAD_FOLDER'], filename))
                return ""
            else:
                return "不支持的文件类型"
    return "上传失败"


@api_blueprint.route("/filedelete")
def filedelete():
    bookname = request.args["bookname"]
    bookpath = os.path.join("bookshelf", bookname)
    reader = current_app.config['reader']
    if os.path.isfile(bookpath):
        reader.delete_file(bookpath)
        return ""
    return "未知的文件"